import React, { useState, useEffect, useRef } from 'react';
import { useRequest, useModel } from 'umi';
import { Row, List, Card, Tabs, Descriptions, Image, message,Collapse,Radio,Space,Tooltip } from 'antd';
import { getMonitoringDevicInfo, getEChartsOption, getMonitoringPhase,getDesignMonitoringPhase } from '@/services/deviceLive';
 import GridLayout from 'react-grid-layout';
import { Responsive, WidthProvider } from 'react-grid-layout';

const ResponsiveGridLayout = WidthProvider(Responsive);


import moment from 'moment'
import ECharts from 'echarts-for-react';


import AlarmTable from '@/pages/monitoring/deviceAlarm';
import { queryDeviceAlarm} from '@/services/sysDeviceAlarm';


import styles from './index.less';


import slg from '@/assets/img/img/slg.png';



const details: React.FC = (props: any) => {
 // const { params } = props.match;
  const params= {id:80000001}
  var { deviceType } = props.location.state;
  const device={deviceId:80000001,deviceTypeId:1};

  const second = useRequest(() => {
    return getDesignMonitoringPhase({...params,deviceType:deviceType.typeId});
  }, {
    pollingInterval: 3000,
    pollingWhenHidden: false
  });


console.log(second)


  const [deviceInfo, setDeviceInfo] = useState<API.DeviceItem>({});
  const [runningData, setRunningData] = useState({});

  const [chartIndex, setChartIndex] = useState(0);

  const [onLineBackgroundColor, setOnLineBackgroundColor] = useState('#8ca1aa');
  const [alarmBackgroundColor, setAlarmBackgroundColor] = useState('#8ca1aa');
  const [tripBackgroundColor, setTripBackgroundColor] = useState('#8ca1aa');

  const [designAttrList, setDesignAttrlist] = useState([]);
  const [designStateList, setDesignStatelist] = useState([]);
  const [attrLayout, setAttrLayout] = useState([])
  const [stateLayout, setStateLayout] = useState([])
  const [items, setItems] = useState([]);

  const [alarmlist, setAlarmlist] = useState<API.SysDeviceAttrItem[]>([]);

  const { initialState,setInitialState } = useModel('@@initialState');
  const { mySocket,dicts,currentUser } = initialState || {};
 

  if (mySocket) {
    mySocket.send(params.id);
    mySocket.onmessage =async function (e) {
     // console.log(`onmessage: ${e.data}`);
      //排除心跳数据
    if ("heartbeat" != e.data&&e.data.indexOf("AlarmData")!=-1) {
        const data = JSON.parse(e.data);
        await setInitialState((s) => ({ ...s, alarmNotices: data.AlarmData }));
      }else  if("heartbeat" != e.data){
        onMessage(e);
      }
    };
  }

  const onMessage = (e:any) => {
    const message = JSON.parse(e.data);
    const rData = message.RunningData||{};
    console.log(rData)

    if(rData.deviceId!=params.id){
      return;
     }
    rData.acquisitionTime = moment().format("YYYY-MM-DD HH:mm:ss");
    if(runningData?.online==0&&rData?.online==1){
       go();
    }
    if(runningData?.alarm==0&&rData?.alarm==1){
        go1();
    }
    if(runningData?.trip==0&&rData?.trip==1){
        go2();
    }
    setRunningData(rData);
  }




  useEffect(() => {
    const setSelectData = async () => {
      let template=deviceType.template;
    
      if(template!=null){
        template=JSON.parse(template);
 
        setItems(template?.tabitem);
        setAttrLayout(template?.attrLayout||[]);
        setDesignAttrlist(template?.attrList);
        setStateLayout(template.stateLayout);
        setDesignStatelist(template.stateList );
       
        console.log(template.stateList )
        console.log(template.attrList )
    
   
      }


    

      getMonitoringDevicInfo(params).then((details) => {
        console.log(details )
        setRunningData(details.runningData||{});
        setDeviceInfo(details.deviceInfo);
        
        if(details.runningData?.online==1){
           go();
        }
        if(details.runningData?.alarm==1){
            go1();
        }
        if(details.runningData?.trip==1){
            go2();
        }
      });

     
      queryDeviceAlarm({"deviceId":params.id,"deviceTypeId":2}).then((alarms) => {
        console.log(alarms )
        setAlarmlist(alarms);

      })

    }
    setSelectData();
 
  }, []);

  const sleep = (t) => {
    return new Promise((res,rej)=>{
        setTimeout(res,t)
    })
}

  async function  go() {
    setOnLineBackgroundColor("yellow");
    await sleep(200)
    setOnLineBackgroundColor("#19377f");
    await  sleep(200)
    go()
}


async function  go1() {
  setAlarmBackgroundColor("red");
  await sleep(300)
  setAlarmBackgroundColor("#19377f");
  await  sleep(300)
  go1()
}
async function  go2() {
  setTripBackgroundColor("red");
  await sleep(300)
  setTripBackgroundColor("#19377f");
  await  sleep(300)
  go2()
}


const getStateColor = (item,index) => {

  if(runningData[item.filed]==1){
   
    return [styles.yuan, item.color=='green'? styles.bgGreen: item.color=='red'? styles.bgRed:styles.bgYellow].join(' ');
  }else{
    return styles.yuan;
  }


}



const designItem = (item,index) => {
 
  var url = null;
  let key=item.i+"";
  // console.log(key)
  switch (item.key) {
    case 1:
      url = (
        <div  key={key} className={styles.dataItem}  data-grid={{...attrLayout[index], static: true}}>
   
         <div className={styles.flexBetween}><Image  width={20}  height={20}  src={'/img/'  + item.picCode}  preview={false} /> <span className={styles.topRight} ></span></div>
         <div className={styles.middleValue}><span className={styles.data} >{runningData[item.filed]||'--' }</span><span className={styles.unit}>{item.unit}</span></div>
         <div className={styles.bottom}>
          <div className={styles.attribute}>{item.text}</div>
         </div >
       </div>
      );
      break;
    case 2:
      url = (
        <div    key={key}  className={styles.dataItem}   data-grid={{...attrLayout[index], static: true}}>
          <div className={styles.flexBetween}><Image  width={20}  height={20}  src={'/img/'  + item.picCode}  preview={false} /> <span className={styles.topRight} ></span></div>
          <div> 
    
          {item.fileds.map((filed ,filedindex) => (
             <div style={{margin: '10px 0 10px 10px',color:'rgb(64 255 255)'}}  className={styles.flex}>  <span style={{color:'rgb(64 255 255)'}}>
             <span className={styles.nameItalic}>{item.fileds[0]?.abb?.substring(0,1)}</span>
             <span>{item.fileds[0]?.abb?.substring(1)}</span>
           </span>
             <div className={styles.dataBox} ><span className={styles.data1} >{runningData[filed.filed]||'--' }</span>{item.unit}</div></div>
            ))}
           
          </div>
          <div className={styles.bottom}>
            <div className={styles.attribute}>{item.text}</div>
          </div >
        </div>
      );
      break;
    case 3:
        url = (  
        <div  key={key} className={styles.dataItem}   data-grid={{...attrLayout[index], static: true}}>
         
        <div className={styles.flexBetween}><Image  width={20}  height={20}  src={'/img/'  + item.picCode}  preview={false} /> <span className={styles.topRight} ></span></div>

        <div style={{margin: '0 0 -2px 10px',color:'rgb(64 255 255)',    marginTop: '-3px'}}  className={styles.flex}>  <span style={{color:'rgb(64 255 255)'}}>
                    <span className={styles.nameItalic}>{item.fileds[0]?.abb?.substring(0,1)}</span>
                    <span>{item.fileds[0]?.abb?.substring(1)}</span>
                  </span><div className={styles.dataBox} ><span className={styles.data1} >{runningData[item.fileds[0]?.filed]||'--' }</span>{item.unit}</div></div>
        <div className={styles.bottom}>
          <div className={styles.attribute}>{item.text}</div>
        </div >
      </div>);
        break;
   case 4:
          url = (
            <div key={key}   className={styles.dataItem}  data-grid={{...attrLayout[index], static: true}}>
               
            <div className={styles.flexBetween}>
              <Image width={20} height={20} src={'/img/'  + item.picCode} preview={false} />{' '}
              <span className={styles.topRight}></span>
            </div>
            <div>
            <div
             
              className={styles.flex}
            >
               <span style={{color:'rgb(64 255 255)'}}>
                    <span className={styles.nameItalic}>{item.fileds[0]?.abb?.substring(0,1)}</span>
                    <span>{item.fileds[0]?.abb?.substring(1)}</span>
                  </span>
              <div className={styles.dataBox}>
                <span className={styles.data1}>{runningData[item.fileds[0]?.filed]||'--' }</span>{item.unit}
              </div>
            </div>
            <div className={styles.flexcenter}>
            {item.fileds.map((filed ,filedindex) => (
             filedindex>0?
              <div className={styles.flexColumn}>
                <span className={styles.data2}>{runningData[filed?.filed]||'--' }</span>
                <span className={styles.attr} >{filed?.abb}</span>
              </div>
              :null
            
            ))}
              
            </div>
          </div>
          <div className={styles.bottom}>
            <div className={styles.attribute}>{item.text}</div>
          </div >
        </div>
  );
          break;
        
          case 5:
            url = (
              <div   key={key}  className={styles.dataItem}  data-grid={{...attrLayout[index], static: true}}>
            
              <div className={styles.flexBetween}>
                <Image width={20} height={20} src={'/img/'  + item.picCode} preview={false} />{' '}
                <span className={styles.topRight}></span>
              </div>
              <div>
                <div className={styles.flexcenter1}>
                {item.fileds.map((filed ,filedindex) => (
               
                  <div className={styles.flexColumn}>
                    <span className={styles.data2}>{runningData[filed?.filed]||'--' }</span>
                    <span className={styles.attr} >{filed?.abb}</span>
                  </div>
                 
                
                ))}
                </div>
              </div>
              <div className={styles.bottom}>
                <div className={styles.attribute}>{item.text}</div>
              </div >
            </div>
    );
      break;
      case 66:
        url = (
          <div  key={key} data-grid={{...attrLayout[index], static: true}}>
            <Card className={ styles.alarmBox}  >
          
            <div className={styles.title1}>{item.text}</div>
            <div className={styles.alrmcontent} >
            {itemAlarm(alarmlist)}
          </div>
          </Card>
          </div> 
        );
        break;
    default:
      url = (
        <div  key={key} data-grid={{...attrLayout[index], static: true}}>
          <Card className={ styles.alarmBox}  >
        
          <div className={styles.title1}>{item.text}</div>
          <div className={styles.alrmcontent} >

           {itemAlarm(alarmlist)}
        </div>
        </Card>
        </div> 
      );
      break;
  }
  return url;
}

const itemAlarm = (list) => {
  console.log(list)
  return   list.map((item,index) => {
    if(list.length>12){
      if(index%2==0){
        return   (<div className={styles.flexBetween}   key={item.id} style={{marginBottom:'12px'}}>
          <div style={{flex:1}} className={styles.flex} key={item.alarmCode}>
            <div className={styles.yuan}    style={runningData[item.key==66?"alarmCode":"tripCode"]==item.alarmCode?{backgroundColor:item.key==66?alarmBackgroundColor:tripBackgroundColor}:{}}></div>
            <span className={styles.baojingText}>{item.alarmDes}</span>
          </div>
          {list.length%2==0||list.length-1>index? <div className={styles.flex} style={{flex:1}}  key={item.alarmCode}>
            <div className={styles.yuan}   ></div>
            <span className={styles.baojingText}>{list[index+1].alarmDes}</span>
          </div>:<div className={styles.flex} style={{flex:1}}></div>}
        </div>)
      }
    }else{
      return   <div className={styles.flex}  style={{marginBottom:'12px'}} key={item.alarmCode}  ><div className={styles.yuan}  ></div><span className={styles.baojingText}>{item.alarmDes}</span></div>
    }
   
  } )
}


  return (
    <div className={styles.main} key={1}>
     
     <div  className={styles.flexBetween} style={{    marginRight: '10px',    alignItems: 'end'}}>
     <div className={styles.flexBetween} style={{flex:5,    alignItems: 'end'}}>
        <div style={{flex:  1}}> 
          <div  className={styles.flex}>  
            <Image    src={slg}  preview={false} />
            <div className={styles.deviceInfo} >
                <div>
                  <span  className={styles.title} > {deviceInfo?.deviceName||'--'} </span>
                  <span className={styles.updateTimeText} > (最新同步时间：{runningData?.acquisitionTime||'--'})</span>
                </div>
                <div className={styles.flexBetween} > 
                  <div>  
                    <span>设备位号：{deviceInfo?.deviceNo||'--'} </span>  
                    <span>&nbsp;  安装位置：{deviceInfo?.areaName||'--'}{deviceInfo?.devicePosition}</span>
                  </div>
                  <div>最新维保日期:{deviceInfo?.latestMaintenanceTime}</div>
                </div>  
            </div>
          </div>
          {/* <div>  
            <span>设备位号：{deviceInfo?.deviceNo||'--'} </span>  
            <span>&nbsp;  安装位置：{deviceInfo?.areaName||'--'}{deviceInfo?.devicePosition||'--'}</span>
          </div>         */}
        </div>
        {/* <div>最新维保日期:{deviceInfo?.latestMaintenanceTime}</div> */}
      </div>
      <div  className={styles.stateContent}>

     <ResponsiveGridLayout  style={{    width:'100%'}}    rowHeight={28}  breakpoints={{lg: 1400, md: 996, sm: 768}} cols={{lg: 16, md: 16, sm: 16}} >
        {designStateList.map((item,index) => (
              <div  key={item.i} className={styles.state}  data-grid={{...stateLayout[index], static: true}}>
                {item.filed=='online'?
                   <div  className={getStateColor(item)}  style={{backgroundColor:onLineBackgroundColor}}></div>
               : <div  className={getStateColor(item)} ></div> }
             
              <span>{item.text}</span>
            </div>
            ))}
      </ResponsiveGridLayout>


      </div>
     </div>
     <div  className={styles.flexBetween} style={{    margin: '12px 0 30px 0',   position: 'relative'}} >
      <ResponsiveGridLayout  style={{    width:'100%'}}    rowHeight={28}  breakpoints={{lg: 1400, md: 996, sm: 768}} cols={{lg: 15, md: 15, sm: 15}} >
       {designAttrList.map((item,index) => (
            designItem(item,index)

          ))}
      </ResponsiveGridLayout> 
  </div>
    <Row style={{marginRight: '0' }} key={6}>
      <div className={styles.tabsTitle}>
        {items.map((item,index) => (
        <>
          {index==0?  <> <a className={chartIndex!=0?styles.a1:[styles.a1,styles.tabcheck1].join(' ')}   onClick={()=>setChartIndex(index)} >三相电流趋势分析</a><div  className={chartIndex!=0?styles.a1after:[styles.a1after,styles.a1afterCheck].join(' ')}></div>   </>
          :index==items.length-1?
          <a className={chartIndex==index?[styles.a3,styles.tabcheck].join(' '):styles.a3}  onClick={()=>setChartIndex(index)}> 报警信息</a>
          : <a className={chartIndex==index?[styles.a2,styles.tabcheck].join(' '):styles.a2}   onClick={()=>setChartIndex(index)}> 三相电压趋势分析</a>
          }
        </> 
        ))}
      </div>
      <Card  className={ styles.modalItem} title={null} style={{width:"100%"}} >
        {second?.data&&items.map((item,index) => (
        item.label!="报警记录"?<ECharts  style={{display:chartIndex==index?'block':'none'}}   option={second?.data[index]} />:   <AlarmTable deviceId={params.id} display={chartIndex==index?'block':'none'} style={{display:chartIndex==index?'block':'none'}}></AlarmTable>
        ))}
      </Card>
    </Row>
    
       
    </div>
  );
};

export default details;